package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.CaseDao;
import com.pojo.CasePojo;
import com.util.JsonUtil;
import com.util.Log;

@WebServlet(urlPatterns={"/user/LoadCaseList", "/admin/LoadCaseList"})
public class LoadCaseList extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String type = request.getParameter("type");
		String pageNumber = request.getParameter("pageNumber");
		String pageSize = request.getParameter("pageSize");
		
		// 当前页
		int intPage = Integer.parseInt((pageNumber == null || pageNumber == "0") ? "1" : pageNumber);
		// 每页显示条数
		int number = Integer.parseInt((pageSize == null || pageSize == "0") ? "10" : pageSize);
		CaseDao dao = new CaseDao();
		String sWhere = " where 1=1 ";

		if (type != null && type.equals("admin")) { // 后台查询所有案例记录
			String caseName = request.getParameter("caseName");
			String caseContent = request.getParameter("caseContent");
			String publishStatus = request.getParameter("publishStatus");

			if (caseName != null && !"".equals(caseName))
				sWhere += " and  caseName like '%" + caseName + "%'";
			if (caseContent != null && !"".equals(caseContent))
				sWhere += " and  content like '%" + caseContent + "%'";
			if (publishStatus != null && !"".equals(publishStatus))
				sWhere += " and publishStatus = "
						+ Integer.parseInt(publishStatus);
		} else { // 前台查询，只显示已发布的记录
			sWhere += "and publishStatus=1 ";
		}

		List<CasePojo> list = dao.loadCase(intPage, number, sWhere);
		
		String sList = "{";
		sList += "\"total\":" + dao.tabCount + ", \"rows\":";
		sList += JsonUtil.ListToJSON(list);
		sList += "}";
		dao.closeAll();
		Log.write(sList);

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		out.println(sList);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
